# view/user.py
import os
from datetime import datetime

import jieba
import jwt
#导入蓝图类
from flask import Blueprint, request, jsonify, current_app
from werkzeug.utils import secure_filename
# 导入连接数据库的组件
from public.sql_connect import get_connent
# 导入token验证的一块
from public.token import token_required, token_required_with_refresh

# 导入封装的公共模块
from public.goods import good_get_public,good_list_public,comment_list_public,brand_list_public,sort_list_public,good_get_public_login

# 创建用户蓝图
good = Blueprint('good_print', __name__)


# 商品列表
@good.route('/list', methods=['GET'])
@token_required_with_refresh
def good_list():
    return good_list_public()

# 获取详情
@good.route('/get/<int:good_id>', methods=['GET'])
@token_required_with_refresh
def get(good_id):
    token = None
    current_user_id = None
    # 从请求头获取token
    if 'Authorization' in request.headers:
        auth_header = request.headers['Authorization']
        # 提取token
        if auth_header.startswith('Bearer '):
            token = auth_header.split(" ")[1]
    try:
        # 解码token
        data = jwt.decode(token, current_app.config['SECRET_KEY'], algorithms=["HS256"])
        # 可以把解码后的数据存入g对象供视图函数使用
        current_user_id = data['id']
    except jwt.ExpiredSignatureError:
        pass
        print("获取商品详情--检查token--过期")
    except jwt.InvalidTokenError:
        pass
        print("获取商品详情--检查token--无效")
    if current_user_id is None:
        print("当前用户未登录：", current_user_id)
        return good_get_public(good_id)
    else:
        print("当前用户已经登录了：", current_user_id)
        return good_get_public_login(current_user_id, good_id)


# 添加商品
@good.route('/add', methods=['POST'])
@token_required
@token_required_with_refresh
def add(current_user_id, current_user_account):
    data = request.get_json()
    if not data:
        return jsonify({
            "code": -1,
            "msg": "请提供参数",
            "data": None
        })

    # 获取参数并设置默认值
    name = data.get('name', '')
    price = data.get('price', '')
    detail = data.get('detail', '')
    discount = data.get('discount', 0)  # 默认折扣为0
    inventory = data.get('inventory', 0)  # 默认库存为0
    picture = data.get('picture', '')
    brandId = data.get('brandId', '')
    sort_id = data.get('sort_id', '')
    oldPrice = data.get('oldPrice', price)  # 默认原价=现价
    available = data.get('available', "true")  # 默认可售
    size = data.get('size', '')
    color = data.get('color', '')

    # 必填字段验证
    required_fields = ['name', 'price', 'inventory', 'picture', 'brandId', 'sort_id']
    for field in required_fields:
        if not data.get(field):
            return jsonify({
                "code": -1,
                "msg": f"请提供{field}参数",
                "data": None
            })

    conn = get_connent()
    cursor = conn.cursor(dictionary=True)
    try:
        cursor.execute(
            """
            INSERT INTO goods
            (name, price, detail, discount, inventory, picture,
             brandId, sort_id, oldPrice, available, user_id,
             size, color, created_at, updated_at)
            VALUES (%s, %s, %s, %s, %s, %s,
                    %s, %s, %s, %s, %s,
                    %s, %s, NOW(), NOW())
            """,
            (name, price, detail, discount, inventory, picture,
             brandId, sort_id, oldPrice, available, current_user_id,
             size, color)
        )
        conn.commit()

        if cursor.rowcount == 0:
            return jsonify({
                "code": -1,
                "msg": "数据库未变化，添加失败",
                "data": None
            })

        # 获取刚插入的商品ID
        good_id = cursor.lastrowid

        return jsonify({
            "code": 0,
            "msg": "添加商品成功",
            "data": {
                "goodId": good_id,
                "name": name,
                "price": price,
                "detail": detail,
                "inventory": inventory,
                "picture": picture
            }
        })

    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"数据库错误: {str(e)}",
            "data": None
        }), 500

    finally:
        cursor.close()
        conn.close()




# 修改商品信息
@good.route('/update/<int:good_id>', methods=['POST'])
@token_required
@token_required_with_refresh
def update(current_user_id, current_user_account, good_id):
    data = request.get_json()
    if not data:
        return jsonify({
            "code": -1,
            "msg": "请求参数不能为空",
            "data": None
        }), 400

    # 构建可更新字段及默认值处理（与添加接口保持一致）
    update_fields = {
        'name': data.get('name'),
        'price': data.get('price'),
        'detail': data.get('detail', ''),
        'discount': data.get('discount', 0),
        'inventory': data.get('inventory', 0),
        'picture': data.get('picture'),
        'brandId': data.get('brandId'),
        'sort_id': data.get('sort_id'),
        'oldPrice': data.get('oldPrice', data.get('price')),  # 默认原价=现价
        'available': data.get('available', "true"),  # 保持字符串类型
        'size': data.get('size', ''),
        'color': data.get('color', '')
    }

    # 过滤掉未提供的字段
    update_data = {k: v for k, v in update_fields.items() if v is not None}

    # 至少需要一个有效字段
    if not update_data:
        return jsonify({
            "code": -1,
            "msg": "未提供任何可更新参数",
            "data": None
        }), 400

    conn = get_connent()
    cursor = conn.cursor(dictionary=True)
    try:
        # 1. 先验证商品是否存在且属于当前用户
        cursor.execute(
            "SELECT id FROM goods WHERE id = %s AND user_id = %s",
            (good_id, current_user_id)
        )
        if not cursor.fetchone():
            return jsonify({
                "code": -1,
                "msg": "商品不存在或无权操作",
                "data": None
            }), 403

        # 2. 构建动态更新SQL
        set_clause = ", ".join([f"{field} = %s" for field in update_data.keys()])
        sql = f"""
            UPDATE goods 
            SET {set_clause}, updated_at = NOW()
            WHERE id = %s
        """
        params = list(update_data.values()) + [good_id]

        # 3. 执行更新
        cursor.execute(sql, params)
        conn.commit()

        # 4. 查询并返回更新后的完整商品信息
        cursor.execute(
            """
            SELECT g.*,
                   b.name as brand_name,
                   s.name as sort_name
            FROM goods g
                     LEFT JOIN brands b ON g.brandId = b.id
                     LEFT JOIN sorts s ON g.sort_id = s.id
            WHERE g.id = %s
            """,
            (good_id,)
        )
        updated_good = cursor.fetchone()

        return jsonify({
            "code": 0,
            "msg": "商品更新成功",
            "data": updated_good
        })

    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"数据库错误: {str(e)}",
            "data": None
        }), 500
    finally:
        cursor.close()
        conn.close()



# 添加库存
@good.route('/add_inventory/<int:good_id>', methods=['POST'])
@token_required
@token_required_with_refresh
def add_inventory(current_user_id, current_user_account, good_id):
    data = request.get_json()
    if not data:
        return jsonify({
            "code": -1,
            "msg": "请提供请求参数",
            "data": None
        })
    if not good_id:
        return jsonify({
            "code": -1,
            "msg": "请提供商品的ID",
            "data": None
        })
    count = int(data.get('count', ''))
    if not count:
        return jsonify({
            "code": -1,
            "msg": "请提供添加数量",
            "data": None
        })
    conn = get_connent()
    cursor = conn.cursor(dictionary=True)
    try:
        cursor.execute(
            'SELECT inventory FROM goods WHERE id = %s AND user_id = %s', (good_id,current_user_id)
        )
        check_result = cursor.fetchone()
        if check_result is None:
            return jsonify({
                "code": -1,
                "msg": "当前商品不存在",
                "data": None
            }),400
        cursor.execute(
            'UPDATE goods SET inventory = inventory + %s WHERE id = %s', (count, good_id)
        )
        conn.commit()
        if cursor.rowcount == 0:
            return jsonify({
                "code": -1,
                "msg": "数据库无改动更新失败",
                "data": None
            }),400
        return jsonify({
            "code": 0,
            "msg": "库存添加成功",
            "data": {
                "good_id": good_id,
                "old_count": check_result.get('inventory'),
                "new_count": check_result.get('inventory') + count
            }
        })
    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"数据库错误: {str(e)}",
            "data": None
        }), 500
    finally:
        cursor.close()
        conn.close()


# 获取某个商品下的评论
@good.route('/comment_list/<int:good_id>', methods=['GET'])
@token_required_with_refresh
def comment_list(good_id):
    return comment_list_public(good_id)



# 文件上传
@good.route('/upload', methods=['POST'])
@token_required
@token_required_with_refresh
def upload(current_user_id, current_user_account):
    print("图片信息：：",request.files)
    if 'file' not in request.files:
        return jsonify({
            "code": -1,
            "msg": "当前未上传图片,字段为file",
            "data": None
        }),400
    file = request.files['file']
    if file.filename == '':
        return jsonify({
            "code": -1,
            "msg": "当前未上传图片,文件为空",
            "data": None
        }),400
    # 允许的文件类型
    ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'webp'}
    MAX_FILE_SIZE = 5 * 1024 * 1024  # 5MB

    # 验证文件类型
    def allowed_file(filename):
        return '.' in filename and \
            filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

    if not allowed_file(file.filename):
        return jsonify({
            "code": -1,
            "msg": f"不支持的文件类型，仅支持: {', '.join(ALLOWED_EXTENSIONS)}",
            "data": None
        }), 400

    # 验证文件大小
    file.seek(0, os.SEEK_END)
    file_length = file.tell()
    file.seek(0)

    if file_length > MAX_FILE_SIZE:
        return jsonify({
            "code": -1,
            "msg": f"文件大小超过限制({MAX_FILE_SIZE // (1024 * 1024)}MB)",
            "data": None
        }), 400
    try:
        # 创建上传目录(如果不存在)
        upload_folder = current_app.config.get('UPLOAD_FOLDER', 'static/goods')
        if not os.path.exists(upload_folder):
            os.makedirs(upload_folder)

        # 生成安全的文件名和路径
        filename = secure_filename(file.filename)
        # 添加时间戳防止重名
        timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
        unique_filename = f"{timestamp}_{current_user_id}_{filename}"
        filepath = os.path.join(upload_folder, unique_filename)

        # 保存文件
        file.save(filepath)

        # 构建可访问的URL
        file_url = f"/{upload_folder}/{unique_filename}"

        return jsonify({
            "code": 0,
            "msg": "文件上传成功",
            "data": {
                "url": file_url,
                "filename": unique_filename,
                "size": file_length
            }
        })

    except Exception as e:
        current_app.logger.error(f"文件上传失败: {str(e)}")
        # 如果发生错误，删除可能已部分上传的文件
        if 'filepath' in locals() and os.path.exists(filepath):
            os.remove(filepath)
        return jsonify({
            "code": -1,
            "msg": "文件上传失败",
            "data": None
        }), 500


# 文件删除
@good.route('/delete_file', methods=['DELETE'])
@token_required
@token_required_with_refresh
def delete_file(current_user_id, current_user_account):
    # 获取要删除的文件URL或文件名
    print("文件路径：",request.get_json())
    data = request.get_json()
    if not data or 'file_url' not in data:
        return jsonify({
            "code": -1,
            "msg": "请提供要删除的文件URL",
            "data": None
        }), 400

    file_url = data['file_url']

    try:
        # 2. 从文件系统中删除文件
        upload_folder = current_app.config.get('UPLOAD_FOLDER', 'static/goods')

        # 从URL中提取文件名
        filename = os.path.basename(file_url)
        filepath = os.path.join(upload_folder, filename)

        if os.path.exists(filepath):
            os.remove(filepath)
        else:
            # 文件不存在于文件系统，但数据库中记录存在
            return jsonify({
                "code": -1,
                "msg": "文件不存在",
                "data": None
            }), 404

        return jsonify({
            "code": 0,
            "msg": "文件删除成功",
            "data": {
                "filename":filename
            }
        })

    except Exception as e:
        current_app.logger.error(f"文件删除失败: {str(e)}")
        return jsonify({
            "code": -1,
            "msg": "文件删除失败",
            "data": None
        }), 500


# 获取品牌的列表
@good.route('/brand_list', methods=['GET'])
@token_required_with_refresh
def brand_list():
    return brand_list_public()



# 获取分类的列表
@good.route('/sort_list', methods=['GET'])
@token_required_with_refresh
def sort_list():
    return sort_list_public()


# 用户收藏商品---收入到购物车
@good.route('/add_car', methods=['POST'])
@token_required
@token_required_with_refresh
def add_car(current_user_id, current_user_account):
    data = request.get_json()
    if not data:
        return jsonify({
            "code": -1,
            "msg": "请提供请求参数",
            "data": None
        })
    good_id = data['good_id']
    count = data['count']
    conn = get_connent()
    cursor = conn.cursor(dictionary=True)
    try:
        # 1. 判断如果有这个商品了就添加数量
        cursor.execute(
            "SELECT id, count FROM shopcars WHERE user_id = %s AND good_id = %s",
            (current_user_id, good_id)
        )
        check_result = cursor.fetchone()
        if check_result:
            # 有就更新
            cursor.execute(
                "UPDATE shopcars SET count = count + %s WHERE user_id = %s AND good_id = %s",
                (count, current_user_id, good_id)
            )
            conn.commit()
            return jsonify({
                "code": 0,
                "msg": "此商品已存在，已经添加数量",
                "data": {
                    "old_count": check_result['count'],
                    "new_count": check_result['count'] + count
                }
            })

        # 2.如果是没有这里商品就新建
        cursor.execute(
            "INSERT INTO shopcars (user_id, good_id, count, created_at, updated_at) VALUES (%s, %s, %s, NOW(), NOW())",
            (current_user_id, good_id, count)
        )
        conn.commit()
        if cursor.rowcount == 0:
            return jsonify({
                "code": -1,
                "msg": "数据库无变化，删除失败",
                "data": None
            })
        return jsonify({
            "code": 0,
            "msg": "添加购物车成功",
            "data": {
                "count": count,
                "good": good_id,
                "user_id": current_user_id,
            }
        })

    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"数据库错误: {str(e)}",
            "data": None
        }), 500
    finally:
        cursor.close()
        conn.close()


# 用户收藏商品---移除到购物车
@good.route("/delete_car/<int:good_id>", methods=['DELETE'])
@token_required
@token_required_with_refresh
def delete_car(current_user_id, current_user_account, good_id):
    conn = get_connent()
    cursor = conn.cursor(dictionary=True)
    try:
        cursor.execute(
            "DELETE FROM shopcars WHERE user_id = %s AND good_id = %s",
            (current_user_id, good_id)
        )
        conn.commit()
        if cursor.rowcount == 0:
            return jsonify({
                "code": -1,
                "msg": "数据库无变化，删除失败",
                "data": None
            })
        return jsonify({
            "code": 0,
            "msg": "购物车移除成功",
            "data": {
                "good_id": good_id
            }
        })

    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"数据库错误: {str(e)}",
            "data": None
        }), 500
    finally:
        cursor.close()
        conn.close()


# 用户收藏商品---清除整个购物车
@good.route("/remove_car", methods=['DELETE'])
@token_required
@token_required_with_refresh
def remove_car(current_user_id, current_user_account):
    conn = get_connent()
    cursor = conn.cursor(dictionary=True)
    try:
        cursor.execute(
            "DELETE FROM shopcars WHERE user_id = %s",
            (current_user_id,)
        )
        conn.commit()
        if cursor.rowcount == 0:
            return jsonify({
                "code": -1,
                "msg": "数据库无变化，删除失败",
                "data": None
            })
        return jsonify({
            "code": 0,
            "msg": "购物车清除成功",
            "data": None
        })

    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"数据库错误: {str(e)}",
            "data": None
        }), 500
    finally:
        cursor.close()
        conn.close()



# 购物车中某个数量的修改
@good.route("/car_item_update/<int:item_id>", methods=['PUT'])
@token_required
@token_required_with_refresh
def car_item_update(current_user_id, current_user_account, item_id):
    data = request.get_json()
    if not data:
        return jsonify({
            "code": -1,
            "msg": "请提供请求参数",
            "data": None
        })
    count = data['count']
    conn = get_connent()
    cursor = conn.cursor(dictionary=True)
    try:
        cursor.execute(
            "UPDATE shopcars SET count = %s WHERE id = %s AND user_id = %s",
            (count, item_id, current_user_id)
        )
        conn.commit()
        if cursor.rowcount == 0:
            return jsonify({
                "code": -1,
                "msg": "数据库未变动，修改失败",
                "data": None
            })
        return jsonify({
            "code": 0,
            "msg": "心愿单修改成",
            "data": {
                "new_count": count,
            }
        })

    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"数据库错误: {str(e)}",
            "data": None
        }), 500
    finally:
        cursor.close()
        conn.close()


# 购物车列表
@good.route("/car_list", methods=['GET'])
@token_required
@token_required_with_refresh
def car_list(current_user_id, current_user_account):
    data = request.get_json()
    if not data:
        return jsonify({
            "code": -1,
            "msg": "请提供请求参数",
            "data": None
        })

    page = data.get('page', 1)  # 默认第1页
    page_size = data.get('page_size', 10)  # 默认每页10条
    keyword = data.get('keyword', '').strip()  # 获取搜索关键词

    offset = (page - 1) * page_size
    conn = get_connent()
    cursor = conn.cursor(dictionary=True)

    try:
        # 基础SQL查询条件
        base_condition = "FROM shopcars s LEFT JOIN goods g ON s.good_id = g.id " \
                         "LEFT JOIN brands ON g.brandId = brands.id " \
                         "LEFT JOIN sorts ON g.sort_id = sorts.id " \
                         "WHERE s.user_id = %s"
        base_params = [current_user_id]

        # 关键词搜索条件
        keyword_condition = ""
        if keyword:
            keyword_condition = " AND (g.name LIKE %s OR g.detail LIKE %s)"
            search_pattern = f"%{keyword}%"
            base_params.extend([search_pattern, search_pattern])

        # 查询总数SQL
        count_sql = f"SELECT COUNT(*) as total {base_condition}{keyword_condition}"
        cursor.execute(count_sql, base_params)
        total_count = cursor.fetchone()['total']

        # 查询数据SQL
        data_sql = f'''
            SELECT 
                s.id as shopcar_id, s.user_id, s.good_id, s.count, 
                s.created_at, s.updated_at,
                g.id as good_id, g.name as good_name, g.detail as good_detail, 
                g.price as good_price, g.oldPrice as good_oldPrice,
                brands.name as brands_name, brands.nameEn as brands_name_en, 
                sorts.name as sorts_name, sorts.nameEn as sorts_name_en
            {base_condition}{keyword_condition}
            ORDER BY shopcar_id DESC 
            LIMIT %s OFFSET %s
        '''
        query_params = base_params.copy()
        query_params.extend([page_size, offset])

        cursor.execute(data_sql, query_params)
        result = cursor.fetchall()

        return jsonify({
            "code": 0,
            "msg": "购物车信息获取成功",
            "data": {
                "list": result,
                "pagination": {
                    "total": total_count,
                    "current_page": page,
                    "page_size": page_size,
                    "total_pages": (total_count + page_size - 1) // page_size
                },
                "keyword": keyword if keyword else None
            }
        })

    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"数据库错误: {str(e)}",
            "data": None
        }), 500
    finally:
        cursor.close()
        conn.close()



# 商品列表---相似商品
@good.route('/similar_list/<int:good_id>', methods=['GET'])
@token_required_with_refresh
def similar_list(good_id):
    data = request.get_json()
    if not data:
        return jsonify({
            "code": -1,
            "msg": "请提供请求参数",
            "data": None
        })
    if good_id is None:
        return jsonify({
            "code": -1,
            "msg": "请提供必要参数",
            "data": None
        })

    page = data.get('page', 1)  # 默认第1页
    page_size = data.get('page_size', 10)  # 默认每页10条
    offset = (page - 1) * page_size

    conn = get_connent()
    cursor = conn.cursor(dictionary=True)

    try:
        # 1. 获取当前商品的信息
        cursor.execute(
            "SELECT id, name, detail FROM goods WHERE id = %s",
            (good_id,)
        )
        current_good = cursor.fetchone()

        if not current_good:
            return jsonify({
                "code": -1,
                "msg": "商品不存在",
                "data": None
            }), 404

        # 2. 提取当前商品的关键词
        name_keywords = list(jieba.cut_for_search(current_good['name']))
        detail_keywords = list(jieba.cut_for_search(current_good['detail']))

        # 合并关键词并去重
        all_keywords = list(set(name_keywords + detail_keywords))

        # 过滤掉停用词和太短的词
        stopwords = {"的", "了", "和", "是", "在", "我", "有", "也", "都", "就"}
        filtered_keywords = [
            # for循环关键词、三目运算符过滤
            word for word in all_keywords if len(word) > 1 and word not in stopwords
        ]

        # 如果关键词太多，取前10个
        if len(filtered_keywords) > 10:
            filtered_keywords = filtered_keywords[:10]

        if not filtered_keywords:
            return jsonify({
                "code": 0,
                "msg": "成功",
                "data": {
                    "list": [],
                    "total": 0
                }
            })

        # 3. 构建模糊查询条件
        conditions = []
        params = []
        for keyword in filtered_keywords:
            conditions.append("(name LIKE %s OR detail LIKE %s)")
            params.extend([f"%{keyword}%", f"%{keyword}%"])

        where_clause = " OR ".join(conditions)

        # 4. 查询相似商品并分页
        # 先获取总数
        count_query = f"""
            SELECT COUNT(*) as total 
            FROM goods 
            WHERE id != %s AND ({where_clause})
        """
        cursor.execute(count_query, [good_id] + params)
        total = cursor.fetchone()['total']

        # 再获取分页数据
        query = f"""
            SELECT id, name, price, picture, detail 
            FROM goods 
            WHERE id != %s AND ({where_clause})
            ORDER BY 
                (CASE WHEN name LIKE %s THEN 1 ELSE 0 END) DESC,
                (CASE WHEN detail LIKE %s THEN 1 ELSE 0 END) DESC
            LIMIT %s OFFSET %s
        """
        # 添加排序条件和分页参数
        primary_keyword = filtered_keywords[0]
        cursor.execute(
            query,
            [good_id] + params + [f"%{primary_keyword}%", f"%{primary_keyword}%", page_size, offset]
        )
        similar_goods = cursor.fetchall()

        return jsonify({
            "code": 0,
            "msg": "成功",
            "data": {
                "list": similar_goods,
                "total": total
            }
        })

    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"服务器错误: {str(e)}",
            "data": None
        }), 500
    finally:
        cursor.close()
        conn.close()




# 商品列表---浏览过的
@good.route('/view_list', methods=['GET'])
@token_required
@token_required_with_refresh
def view_list(current_user_id, current_user_account):
    data = request.get_json()
    if not data:
        return jsonify({"code": -1, "msg": "请求数据不能为空", "data": None}), 400

    page = int(data.get('page', 1))
    page_size = int(data.get('page_size', 10))
    offset = (page - 1) * page_size
    keywords = data.get('keywords', '')
    price_start = data.get('price_start', 0)
    price_end = data.get('price_end', 0)
    brandId = data.get('brandId', '')
    sort_id = data.get('sort_id', '')

    conn = get_connent()
    cursor = conn.cursor(dictionary=True)

    try:
        params = [current_user_id]  # 添加当前用户ID作为第一个参数
        count_params = [current_user_id]

        # 基础SQL查询
        sql = '''
              SELECT v.id         as view_id,
                     v.created_at as view_time,
                     g.id         as good_id,
                     g.name,
                     g.detail,
                     g.picture,
                     g.price,
                     g.discount,
                     g.oldPrice,
                     g.inventory,
                     g.brandId,
                     g.salesCount,
                     g.commentCount,
                     g.collectCount,
                     g.available, 
                     g.sort_id, 
                     b.name       as brand_name, 
                     b.nameEn     as brand_name_en, 
                     s.name       as sort_name, 
                     s.nameEn     as sort_name_en
              FROM views v
                       LEFT JOIN goods g ON v.good_id = g.id
                       LEFT JOIN brands b ON g.brandId = b.id
                       LEFT JOIN sorts s ON g.sort_id = s.id
              WHERE v.user_id = %s 
              '''

        count_sql = '''
                    SELECT COUNT(*) as total
                    FROM views v
                             LEFT JOIN goods g ON v.good_id = g.id
                    WHERE v.user_id = %s 
                    '''

        # 添加筛选条件
        if keywords:
            sql += " AND (g.name LIKE %s OR g.detail LIKE %s)"
            count_sql += " AND (g.name LIKE %s OR g.detail LIKE %s)"
            params.extend([f'%{keywords}%', f'%{keywords}%'])
            count_params.extend([f'%{keywords}%', f'%{keywords}%'])

        if price_start:
            sql += " AND g.price >= %s"
            count_sql += " AND g.price >= %s"
            params.append(price_start)
            count_params.append(price_start)

        if price_end:
            sql += " AND g.price <= %s"
            count_sql += " AND g.price <= %s"
            params.append(price_end)
            count_params.append(price_end)

        if brandId:
            sql += " AND g.brandId = %s"
            count_sql += " AND g.brandId = %s"
            params.append(brandId)
            count_params.append(brandId)

        if sort_id:
            sql += " AND g.sort_id = %s"
            count_sql += " AND g.sort_id = %s"
            params.append(sort_id)
            count_params.append(sort_id)

        # 排序和分页
        sql += ' ORDER BY v.created_at DESC'
        sql += ' LIMIT %s OFFSET %s'
        params.extend([page_size, offset])

        # 执行查询
        cursor.execute(sql, params)
        view_list = cursor.fetchall()

        cursor.execute(count_sql, count_params)
        total = cursor.fetchone().get('total')

        return jsonify({
            "code": 0,
            "msg": "浏览过的商品列表获取成功",
            "data": {
                "list": view_list,
                "total": total
            }
        })

    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"服务器错误: {str(e)}",
            "data": None
        }), 500
    finally:
        cursor.close()
        conn.close()



# 商品---收藏
@good.route('/collect/<int:good_id>', methods=['POST'])
@token_required
@token_required_with_refresh
def collect(current_user_id, current_user_account, good_id):
    if good_id is None:
        return jsonify({
            "code": -1,
            "msg": "请提供必要参数",
            "data": None
        })
    conn = get_connent()
    cursor = conn.cursor(dictionary=True)
    try:
        cursor.execute('SELECT id FROM goods WHERE id = %s', (good_id,))
        good_info = cursor.fetchone()
        if good_info is None:
            return jsonify({
                "code": -1,
                "msg": "当前商品不存在",
                "data": None
            })
        # 1. 查看是否已经收藏
        cursor.execute(
            "SELECT id FROM collects WHERE good_id = %s AND user_id = %s", (good_id, current_user_id)
        )
        check_result = cursor.fetchone()
        if check_result is None:
            cursor.execute(
                "INSERT INTO collects (good_id, user_id, created_at, updated_at) VALUES (%s, %s, NOW(), NOW())",
                (good_id, current_user_id)
            )
            # conn.commit()
            # 接着，添加goods的数量
            cursor.execute(
                "UPDATE goods SET collectCount = collectCount + 1 WHERE id = %s", (good_id,)
            )
            conn.commit()
            return jsonify({
                "code": 0,
                "msg": "收藏成功",
                "data": {
                    "good_id": good_id,
                    "user_id": current_user_id,
                }
            })
        return jsonify({
            "code": -1,
            "msg": "你已经收藏此商品",
            "data": None
        })



    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"服务器错误: {str(e)}",
            "data": None
        }), 500
    finally:
        cursor.close()
        conn.close()



# 商品列表---收藏
@good.route('/collect_list', methods=['GET'])
@token_required
@token_required_with_refresh
def collect_list(current_user_id, current_user_account):
    data = request.get_json()
    if not data:
        return jsonify({"code": -1, "msg": "请求数据不能为空", "data": None}), 400

    page = int(data.get('page', 1))
    page_size = int(data.get('page_size', 10))
    offset = (page - 1) * page_size
    keywords = data.get('keywords', '')
    price_start = data.get('price_start', 0)
    price_end = data.get('price_end', 0)
    brandId = data.get('brandId', '')
    sort_id = data.get('sort_id', '')
    is_reduce = data.get('is_reduce', False)
    is_have_inventory = data.get('is_have_inventory', False)

    conn = get_connent()
    cursor = conn.cursor(dictionary=True)

    try:
        params = [current_user_id]
        count_params = [current_user_id]

        sql = '''
              SELECT c.id         as collect_id, 
                     c.created_at as collect_time, 
                     g.id         as good_id, 
                     g.name, 
                     g.detail, 
                     g.picture, 
                     g.price, 
                     g.discount, 
                     g.oldPrice, 
                     g.inventory, 
                     g.brandId, 
                     g.salesCount, 
                     g.commentCount, 
                     g.collectCount, 
                     g.available, 
                     g.sort_id, 
                     b.name       as brand_name, 
                     b.nameEn     as brand_name_en, 
                     s.name       as sort_name,
                     s.nameEn     as sort_name_en,
                     CASE WHEN g.price < g.oldPrice THEN TRUE ELSE FALSE END as is_reduced
              FROM collects c
                       LEFT JOIN goods g ON c.good_id = g.id
                       LEFT JOIN brands b ON g.brandId = b.id
                       LEFT JOIN sorts s ON g.sort_id = s.id
              WHERE c.user_id = %s 
              '''

        count_sql = '''
                    SELECT COUNT(*) as total
                    FROM collects c
                             LEFT JOIN goods g ON c.good_id = g.id
                    WHERE c.user_id = %s 
                    '''

        # 添加筛选条件
        if keywords:
            sql += " AND (g.name LIKE %s OR g.detail LIKE %s)"
            count_sql += " AND (g.name LIKE %s OR g.detail LIKE %s)"
            params.extend([f'%{keywords}%', f'%{keywords}%'])
            count_params.extend([f'%{keywords}%', f'%{keywords}%'])

        if price_start:
            sql += " AND g.price >= %s"
            count_sql += " AND g.price >= %s"
            params.append(price_start)
            count_params.append(price_start)

        if price_end:
            sql += " AND g.price <= %s"
            count_sql += " AND g.price <= %s"
            params.append(price_end)
            count_params.append(price_end)

        if brandId:
            sql += " AND g.brandId = %s"
            count_sql += " AND g.brandId = %s"
            params.append(brandId)
            count_params.append(brandId)

        if sort_id:
            sql += " AND g.sort_id = %s"
            count_sql += " AND g.sort_id = %s"
            params.append(sort_id)
            count_params.append(sort_id)

        # 新增筛选条件：是否降价
        if is_reduce:
            sql += " AND g.price < g.oldPrice"
            count_sql += " AND g.price < g.oldPrice"

        # 新增筛选条件：是否有货
        if is_have_inventory:
            sql += " AND g.inventory > 0"
            count_sql += " AND g.inventory > 0"

        # 排序和分页
        sql += ' ORDER BY c.created_at DESC'
        sql += ' LIMIT %s OFFSET %s'
        params.extend([page_size, offset])

        # 执行查询
        cursor.execute(sql, params)
        collect_list = cursor.fetchall()

        cursor.execute(count_sql, count_params)
        total = cursor.fetchone().get('total')

        return jsonify({
            "code": 0,
            "msg": "收藏商品列表获取成功",
            "data": {
                "list": collect_list,
                "total": total,
                "filters": {
                    "is_reduce": is_reduce,
                    "is_have_inventory": is_have_inventory
                }
            }
        })

    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"服务器错误: {str(e)}",
            "data": None
        }), 500
    finally:
        cursor.close()
        conn.close()



# 收货地址添加
@good.route('/address/add', methods=['POST'])
@token_required
@token_required_with_refresh
def address_add(current_user_id, current_user_account):
    data = request.get_json()
    if not data or 'address' not in data:
        return jsonify({"code": -1, "msg": "请求数据不能为空", "data": None}), 400

    address = data['address']
    is_def = data.get('is_def', 1)  # 默认为非默认地址

    conn = get_connent()
    cursor = conn.cursor(dictionary=True)

    try:
        # 如果设置为默认地址，先取消其他默认地址
        if is_def == 0:
            cursor.execute(
                "UPDATE adress SET is_def = 1 WHERE user_id = %s AND is_def = 0",
                (current_user_id,)
            )

        # 插入新地址
        cursor.execute(
            "INSERT INTO adress (user_id, address, is_def, created_at, updated_at) "
            "VALUES (%s, %s, %s, NOW(), NOW())",
            (current_user_id, address, is_def)
        )
        conn.commit()

        return jsonify({
            "code": 0,
            "msg": "收货地址添加成功",
            "data": {
                "address_id": cursor.lastrowid
            }
        })

    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"服务器错误: {str(e)}",
            "data": None
        }), 500
    finally:
        cursor.close()
        conn.close()


# 删除收货地址
@good.route('/address/delete', methods=['POST'])
@token_required
@token_required_with_refresh
def address_delete(current_user_id, current_user_account):
    data = request.get_json()
    if not data or 'address_id' not in data:
        return jsonify({"code": -1, "msg": "请求数据不能为空", "data": None}), 400

    address_id = data['address_id']

    conn = get_connent()
    cursor = conn.cursor(dictionary=True)

    try:
        # 检查地址是否属于当前用户
        cursor.execute(
            "SELECT id FROM adress WHERE id = %s AND user_id = %s",
            (address_id, current_user_id)
        )
        if not cursor.fetchone():
            return jsonify({"code": -1, "msg": "地址不存在或无权操作", "data": None}), 403

        # 删除地址
        cursor.execute(
            "DELETE FROM adress WHERE id = %s",
            (address_id,)
        )
        conn.commit()

        return jsonify({
            "code": 0,
            "msg": "收货地址删除成功",
            "data": {
                "address_id": address_id,
            }
        })

    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"服务器错误: {str(e)}",
            "data": None
        }), 500
    finally:
        cursor.close()
        conn.close()


# 设置默认地址
@good.route('/address/set_default', methods=['POST'])
@token_required
@token_required_with_refresh
def address_set_default(current_user_id, current_user_account):
    data = request.get_json()
    if not data or 'address_id' not in data:
        return jsonify({"code": -1, "msg": "请求数据不能为空", "data": None}), 400

    address_id = data['address_id']

    conn = get_connent()
    cursor = conn.cursor(dictionary=True)

    try:
        # 检查地址是否属于当前用户
        cursor.execute(
            "SELECT id FROM adress WHERE id = %s AND user_id = %s",
            (address_id, current_user_id)
        )
        if not cursor.fetchone():
            return jsonify({"code": -1, "msg": "地址不存在或无权操作", "data": None}), 403

        # 先取消所有默认地址
        cursor.execute(
            "UPDATE adress SET is_def = 1 WHERE user_id = %s",
            (current_user_id,)
        )

        # 设置新地默认地址
        cursor.execute(
            "UPDATE adress SET is_def = 0 WHERE id = %s",
            (address_id,)
        )
        conn.commit()

        return jsonify({
            "code": 0,
            "msg": "默认地址设置成功",
            "data": {
                "address_id": address_id,
            }
        })

    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"服务器错误: {str(e)}",
            "data": None
        }), 500
    finally:
        cursor.close()
        conn.close()


# 收获地址列表
@good.route('/address/list', methods=['GET'])
@token_required
@token_required_with_refresh
def address_list(current_user_id, current_user_account):
    data = request.get_json()
    if not data:
        return jsonify({"code": -1, "msg": "请求数据不能为空", "data": None}), 400

    page = int(data.get('page', 1))
    page_size = int(data.get('page_size', 10))
    offset = (page - 1) * page_size

    conn = get_connent()
    cursor = conn.cursor(dictionary=True)

    try:
        # 查询地址列表
        cursor.execute(
            "SELECT * FROM adress WHERE user_id = %s "
            "ORDER BY is_def ASC, created_at DESC "
            "LIMIT %s OFFSET %s",
            (current_user_id, page_size, offset)
        )
        address_list = cursor.fetchall()

        # 查询总数
        cursor.execute(
            "SELECT COUNT(*) as total FROM adress WHERE user_id = %s",
            (current_user_id,)
        )
        total = cursor.fetchone().get('total')

        return jsonify({
            "code": 0,
            "msg": "收货地址列表获取成功",
            "data": {
                "list": address_list,
                "total": total
            }
        })

    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"服务器错误: {str(e)}",
            "data": None
        }), 500
    finally:
        cursor.close()
        conn.close()


# 获取收货地址详情
@good.route('/address/get', methods=['GET'])
@token_required
@token_required_with_refresh
def address_get(current_user_id, current_user_account):
    data = request.get_json()
    if not data or 'address_id' not in data:
        return jsonify({"code": -1, "msg": "请求数据不能为空", "data": None}), 400

    address_id = data['address_id']

    conn = get_connent()
    cursor = conn.cursor(dictionary=True)

    try:
        cursor.execute(
            "SELECT * FROM adress WHERE id = %s AND user_id = %s",
            (address_id, current_user_id)
        )
        address = cursor.fetchone()

        if not address:
            return jsonify({"code": -1, "msg": "地址不存在或无权查看", "data": None}), 404

        return jsonify({
            "code": 0,
            "msg": "收货地址获取成功",
            "data": address
        })

    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"服务器错误: {str(e)}",
            "data": {
                "address_id": address_id,
            }
        }), 500
    finally:
        cursor.close()
        conn.close()



# 修改收获信息
@good.route('/address/update', methods=['POST'])
@token_required
@token_required_with_refresh
def address_update(current_user_id, current_user_account):
    data = request.get_json()
    if not data or 'address_id' not in data or 'address' not in data:
        return jsonify({"code": -1, "msg": "请求数据不能为空", "data": None}), 400

    address_id = data['address_id']
    address = data['address']
    is_def = data.get('is_def')

    conn = get_connent()
    cursor = conn.cursor(dictionary=True)

    try:
        # 检查地址是否属于当前用户
        cursor.execute(
            "SELECT id FROM adress WHERE id = %s AND user_id = %s",
            (address_id, current_user_id)
        )
        if not cursor.fetchone():
            return jsonify({"code": -1, "msg": "地址不存在或无权操作", "data": None}), 403

        # 如果设置为默认地址，先取消其他默认地址
        if is_def == 0:
            cursor.execute(
                "UPDATE adress SET is_def = 1 WHERE user_id = %s AND is_def = 0",
                (current_user_id,)
            )

        # 更新地址信息
        update_sql = "UPDATE adress SET address = %s, updated_at = NOW()"
        params = [address]

        if is_def is not None:
            update_sql += ", is_def = %s"
            params.append(is_def)

        update_sql += " WHERE id = %s"
        params.append(address_id)

        cursor.execute(update_sql, params)
        conn.commit()

        return jsonify({
            "code": 0,
            "msg": "收货地址更新成功",
            "data": {
                "address_id": address_id,
            }
        })

    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"服务器错误: {str(e)}",
            "data": None
        }), 500
    finally:
        cursor.close()
        conn.close()


# 根据当前的大分类去找底下的子类
@good.route('/parents_sort/sort',methods=['GET'])
@token_required_with_refresh
def parents_sort_child():
    data = request.get_json()
    if not data or 'parent_id' not in data:
        return jsonify({"code": -1, "msg": "缺少必要参数", "data": None}), 400
    parent_id = data['parent_id']
    conn = get_connent()
    cursor = conn.cursor(dictionary=True)
    try:
        cursor.execute(
            "SELECT id,name FROM sorts WHERE father_id = %s",
            (parent_id,)
        )
        child_list = cursor.fetchall()
        cursor.execute(
            "SELECT COUNT(id) as total FROM sorts WHERE father_id = %s",
            (parent_id,)
        )
        child_total = cursor.fetchone()['total']
        return jsonify({
            "code": 0,
            "msg": "子类获取成功",
            "data": {
                "child_list": child_list,
                "child_total": child_total,
            }
        })

    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"服务器错误: {str(e)}",
            "data": None
        }), 500
    finally:
        cursor.close()
        conn.close()


# 根据当前的大类去找底下所有的品牌
@good.route('/parents_sort/brand',methods=['GET'])
@token_required_with_refresh
def parents_sort_brand():
    data = request.get_json()
    if not data or 'parent_id' not in data:
        return jsonify({"code": -1, "msg": "缺少必要参数", "data": None}), 400
    parent_id = data['parent_id']
    conn = get_connent()
    cursor = conn.cursor(dictionary=True)
    try:
        cursor.execute(
            '''
            SELECT g.brandId, b.name, b.nameEn
            FROM goods g
            LEFT JOIN brands b ON b.id = g.brandId
            WHERE g.sort_id = %s
            ''',
            (parent_id,)
        )
        brand_list = cursor.fetchall()
        cursor.execute(
            '''
            SELECT COUNT(g.id) as total
            FROM goods g
                     LEFT JOIN brands b ON b.id = g.brandId
            WHERE g.sort_id = %s
            ''',
            (parent_id,)
        )
        brand_total = cursor.fetchone()['total']
        return jsonify({
            "code": 0,
            "msg": "类中品牌获取成功",
            "data": {
                "brand_list": brand_list,
                "brand_total": brand_total,
            }
        })

    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"服务器错误: {str(e)}",
            "data": None
        }), 500
    finally:
        cursor.close()
        conn.close()


# 获取一级分类
@good.route('/parents_list',methods=['GET'])
@token_required_with_refresh
def parents_list():
    conn = get_connent()
    cursor = conn.cursor(dictionary=True)
    try:
        cursor.execute(
            "SELECT id, name, nameEn FROM sorts WHERE father_id = 0",
        )
        parent_list = cursor.fetchall()
        cursor.execute(
            "SELECT COUNT(id) as total FROM sorts WHERE father_id = 0"
        )
        parent_total = cursor.fetchone()['total']
        return jsonify({
            "code": 0,
            "msg": "获取全部父级分类",
            "data": {
                "parent_list": parent_list,
                "parent_total": parent_total,
            }
        })

    except Exception as e:
        conn.rollback()
        return jsonify({
            "code": -1,
            "msg": f"服务器错误: {str(e)}",
            "data": None
        }), 500
    finally:
        cursor.close()
        conn.close()

